package com.example.springboot_demo.controller;

import com.alibaba.fastjson2.JSON;
import com.example.springboot_demo.pojo.Book;
import com.example.springboot_demo.pojo.Cart;
import com.example.springboot_demo.pojo.CartData;
import com.example.springboot_demo.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@RestController
public class CartController {
    @Autowired
    CartService cartService;

    //把书籍加入购物车
    @RequestMapping(value = "/addBookToCart", method = RequestMethod.POST)
    public Cart<Book> addBookToCart(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {

        Cart<Book> cart = JSON.parseObject(JSON.toJSONString(map.get("cart")), Cart.class);
        int bookId = Integer.parseInt(map.get("bookId").toString());

        if (cart == null) {
            cart = new Cart<>();
        }
        CartData<Book> cartDataBook = cartService.cartData_add(bookId);
        cart.addCartData_book(cartDataBook);
        return cart;
    }


    //删除一种类型的图书
    @RequestMapping(value = "/decreaseBook", method = RequestMethod.POST)
    public Cart<Book> decrease(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
        Cart<Book> cart = JSON.parseObject(JSON.toJSONString(map.get("cart")), Cart.class);
        int bookId = Integer.parseInt(map.get("bookId").toString());
        cart.decrease_book(bookId);
        return cart;
    }


    //一种类型图书的数量减 1
    @RequestMapping(value = "/deleteCartData", method = RequestMethod.POST)
    public Cart<Book> deleteCartData(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
        Cart<Book> cart = JSON.parseObject(JSON.toJSONString(map.get("cart")), Cart.class);
        int bookId = Integer.parseInt(map.get("bookId").toString());
        cart.deleteCartData_book(bookId);
        return cart;
    }

    //清空购物车
    @RequestMapping(value = "/clearCart", method = RequestMethod.POST)
    public Cart<Book> clearCart(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
        Cart<Book> cart = JSON.parseObject(JSON.toJSONString(map.get("cart")), Cart.class);
        cart.clearCart();
        return cart;
    }
}
